import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zdl
 * @Description
 * @create 2021-05-21 10:55
 */
public class DeviceClient {
    public static Socket client = null;
    public static DataOutputStream out = null;

    public static void main(String[] args) throws Exception {
        //String host = "127.0.0.1";
        String host = "112.74.176.68";
        // int port = 9098;
        int port = 9090;
        client = new Socket();
        client.connect(new InetSocketAddress(host, port));
        System.out.println("连接成功.......");
        OutputStream outToServer = client.getOutputStream();
        DataOutputStream out = new DataOutputStream(outToServer);
        //开机上报
        String imei = "900115470000876";
        String sendJson = "*WT," + imei + ",POWERON,105041,m3,595,wt_cat1_01_30,V,2742800135,2742800135,,FFDFFFFF#";
        byte[] outByte = sendJson.getBytes("utf-8");
        out.write(outByte);
        out.flush();

        // 开启心跳
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new ExecuteHeartThread(out, imei));
        //读
        new Thread(() -> {
            try {
                InputStream ss = client.getInputStream();
                InputStreamReader isr = new InputStreamReader(ss);
                BufferedReader br = new BufferedReader(isr);
                StringBuffer s = new StringBuffer();
                int b = -1;
                String sendData = null;
                while ((b = ss.read()) != -1) {
                    char c =(char) b;
                    s.append(c);
                    if (c=='#') {
                        System.out.println("service:" + s.toString());
                        if (s.indexOf(".D1.") > 1) {
                            sendData = "*WT," + imei + ",V4,D1,164815,164937,V,0.0000,S,0.0000,W,0.00,0,460,11,0,1,30501,124968449,108,108,0,73,240521,FFFDFFFF#";
                        }
                        s.setLength(0);
                    }
                    if (sendData != null) {
                        byte[] outByte1 = sendData.getBytes("utf-8");
                        out.write(outByte1);
                        out.flush();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }).start();

    }
}
